package com.group.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group.activity.dao.SecondKillConfigurationDao;
import com.group.activity.entity.SeckillSkuRelationshipEntity;
import com.group.activity.entity.SecondKillConfigurationEntity;
import com.group.activity.service.SeckillSkuRelationshipService;
import com.group.activity.service.SecondKillConfigurationService;
import com.group.common.utils.PageUtils;
import com.group.common.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("secondKillConfigurationService")
public class SecondKillConfigurationServiceImpl extends ServiceImpl<SecondKillConfigurationDao, SecondKillConfigurationEntity> implements SecondKillConfigurationService {
    @Autowired
    SeckillSkuRelationshipService seckillSkuRelationshipService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SecondKillConfigurationEntity> page = this.page(
                new Query<SecondKillConfigurationEntity>().getPage(params),
                new QueryWrapper<SecondKillConfigurationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SecondKillConfigurationEntity> getSeckillLasted3DaysInfo() {
        List<SecondKillConfigurationEntity> entities = baseMapper.selectList(new QueryWrapper<SecondKillConfigurationEntity>().between("start_time", startTime(), endTime()));
        if (entities!=null){
            List<SecondKillConfigurationEntity> collect = entities.stream().map(item -> {
                List<SeckillSkuRelationshipEntity> seckillSkuRelationshipEntities = seckillSkuRelationshipService.list(new QueryWrapper<SeckillSkuRelationshipEntity>().eq("seckill_session_id", item.getId()));
                item.setSeckillSkuRelationshipEntities(seckillSkuRelationshipEntities);
                return item;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private String startTime(){
        LocalDate now = LocalDate.now();
        LocalTime min = LocalTime.MIN;
        LocalDateTime of = LocalDateTime.of(now, min);
        return of.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    private String endTime(){
        LocalDate now = LocalDate.now().plusDays(2);
        LocalTime max = LocalTime.MAX;
        LocalDateTime of = LocalDateTime.of(now, max);
        return of.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

}